package com.mccree.cloud.controller;

import cn.hutool.json.JSONUtil;
import com.mccree.cloud.common.R;
import com.mccree.cloud.constans.ServerConstants;
import com.mccree.cloud.dao.entity.PaymentEntity;
import com.mccree.cloud.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: MccRee
 * @Date: 2022/5/31 17:18
 */
@RestController
@Slf4j
@RequestMapping("sys/pay")
@Api(tags = "支付模块")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String port;

    @Resource
    private DiscoveryClient discoveryClient;

    /**
     * 查看当前服务信息
     * @return
     */
    @ApiOperation("查看当前服务信息")
    @GetMapping("/getServiceInfo")
    public R getServiceInfo(){
        try {
            List<String> services = discoveryClient.getServices();
            String servicesMsg = JSONUtil.formatJsonStr(JSONUtil.toJsonStr(services));
            log.info("服务信息:{},描述:{}",servicesMsg,discoveryClient.description());
            List<ServiceInstance> instances = discoveryClient.getInstances(ServerConstants.PAYMENT_SERVER);
            instances.forEach(c -> {
                log.info("主机:{},id:{},端口:{},地址:{}",c.getHost(),c.getServiceId(),c.getPort(),c.getUri());
            });
            return R.ok(discoveryClient);
        }catch (Exception e){
            log.error("GET_SERVICE_INFO_ERROR:",e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 仅供测试
     * @return
     */
    @ApiOperation("获取所有的支付数据")
    @GetMapping("/getAll")
    public R<PaymentEntity> getAll(){
        try {
            List<PaymentEntity> all = paymentService.getAll();
            return R.ok(all,port);
        }catch (Exception e){
            log.error("PAY_GET_ALL_ERROR:",e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 创建一条订单
     * @param entity
     * @return
     */
    @ApiOperation("创建一条订单")
    @PostMapping("/create")
    public R create(@RequestBody PaymentEntity entity){
        try {
            paymentService.save(entity);
            return R.ok("创建成功");
        }catch (Exception e){
            log.error("PAY_CREATE_ERROR:",e);
            return R.error(e.getMessage());
        }
    }
}
